<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"zengchao_workspace.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="状态在不同的语言中,线程状态定义有细微的不同,但是都是大同小异.在java中,在Thread类中有一个枚举,记载了线程的6个状态.  NEW(初始):新创建一个线程,但是还没有调用线程的start()方法. RUNNABLE(可运行):在java中,把运行running和就绪ready状态都称为RUNABLE状态.在创建完线程后,调用线程的start()方法,线程将进入该状态.该线程在线程池中等待">
<meta property="og:type" content="article">
<meta property="og:title" content="(三)线程的状态">
<meta property="og:url" content="https://zengchao_workspace.gitee.io/2020/09/10/3.%E7%BA%BF%E7%A8%8B%E7%9A%84%E7%8A%B6%E6%80%81/index.html">
<meta property="og:site_name" content="一只小菜鸟">
<meta property="og:description" content="状态在不同的语言中,线程状态定义有细微的不同,但是都是大同小异.在java中,在Thread类中有一个枚举,记载了线程的6个状态.  NEW(初始):新创建一个线程,但是还没有调用线程的start()方法. RUNNABLE(可运行):在java中,把运行running和就绪ready状态都称为RUNABLE状态.在创建完线程后,调用线程的start()方法,线程将进入该状态.该线程在线程池中等待">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2019/10/28/N4RmcJKCjpVHOrG.jpg">
<meta property="article:published_time" content="2020-09-10T10:11:49.000Z">
<meta property="article:modified_time" content="2020-09-10T10:39:36.877Z">
<meta property="article:author" content="菜鸟">
<meta property="article:tag" content="多线程">
<meta property="article:tag" content="初级">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2019/10/28/N4RmcJKCjpVHOrG.jpg">

<link rel="canonical" href="https://zengchao_workspace.gitee.io/2020/09/10/3.%E7%BA%BF%E7%A8%8B%E7%9A%84%E7%8A%B6%E6%80%81/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>(三)线程的状态 | 一只小菜鸟</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一只小菜鸟</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">码农相关</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://zengchao_workspace.gitee.io/2020/09/10/3.%E7%BA%BF%E7%A8%8B%E7%9A%84%E7%8A%B6%E6%80%81/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="菜鸟">
      <meta itemprop="description" content="编程,码农,it,技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一只小菜鸟">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          (三)线程的状态
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-09-10 18:11:49 / 修改时间：18:39:36" itemprop="dateCreated datePublished" datetime="2020-09-10T18:11:49+08:00">2020-09-10</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="状态"><a href="#状态" class="headerlink" title="状态"></a>状态</h2><p>在不同的语言中,线程状态定义有细微的不同,但是都是大同小异.在java中,在<code>Thread</code>类中有一个枚举,记载了线程的6个状态.</p>
<ul>
<li><code>NEW(初始)</code>:新创建一个线程,但是还没有调用线程的start()方法.</li>
<li><code>RUNNABLE(可运行)</code>:在java中,把运行running和就绪ready状态都称为RUNABLE状态.在创建完线程后,调用线程的start()方法,线程将进入该状态.该线程在线程池中等待系统调度获取cpu使用权时,就是ready.获取到cpu使用权时,就是running.</li>
<li><code>BLOCKED(阻塞)</code>:线程在等待一个锁而无法进入同步块.</li>
<li><code>WAITING(等待)</code>:一个正在无限等待另一个线程执行一个特别的动的线程就处于该状态.</li>
<li><code>TIMED_WAITING(超时等待)</code>:一个正在限时等待另一个线程执行一个动作的线程处于这一状态.基本上与WAITING一样,只不过多了时限而已.</li>
<li><code>TERMINATED(终止)</code>:已退出的线程处于这种状态.</li>
</ul>
<h2 id="状态变化"><a href="#状态变化" class="headerlink" title="状态变化"></a>状态变化</h2><p><img src="https://i.loli.net/2019/10/28/N4RmcJKCjpVHOrG.jpg" alt="线程状态转换图.jpg"></p>
<h2 id="BLOCKED-阻塞"><a href="#BLOCKED-阻塞" class="headerlink" title="BLOCKED(阻塞)"></a>BLOCKED(阻塞)</h2><p>线程何时会进入<code>BLOCKED</code>状态呢?总结下来就是线程在等待一个监视锁,这个时候就会进入该状态.例如下面代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlockDemo1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">       Counter counter = <span class="keyword">new</span> Counter();</span><br><span class="line">        Thread t1 = <span class="keyword">new</span> Thread(() -&gt; counter.increase());</span><br><span class="line">        t1.setName(<span class="string">&quot;线程1&quot;</span>);</span><br><span class="line">        t1.start();</span><br><span class="line">        <span class="comment">//确保线程1先获取到锁</span></span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line">        Thread t2 = <span class="keyword">new</span> Thread(() -&gt; counter.increase());</span><br><span class="line">        t2.setName(<span class="string">&quot;线程2&quot;</span>);</span><br><span class="line">        t2.start();</span><br><span class="line">        <span class="comment">//确保线程2已经开始运行</span></span><br><span class="line">        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">        <span class="comment">//打印线程2状态</span></span><br><span class="line">        System.out.println(<span class="string">&quot;t2.getState() = &quot;</span> + t2.getState());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Counter</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> number = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">increase</span><span class="params">()</span></span>&#123;</span><br><span class="line">        number++;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">5000L</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的示例代码中,线程1先获取到<code>counter实例锁</code>,而线程2没有获取到锁,这将引发线程2进入BLOCKED状态.这是一种比较常见的情况.另外还有一种情况,如下代码所示:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BlockDemo2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        Account account = <span class="keyword">new</span> Account();</span><br><span class="line"></span><br><span class="line">        Thread t1 = <span class="keyword">new</span> Thread(() -&gt; account.get(<span class="number">100</span>));</span><br><span class="line">        t1.setName(<span class="string">&quot;取钱线程&quot;</span>);</span><br><span class="line">        t1.start();</span><br><span class="line"></span><br><span class="line">        Thread.sleep(<span class="number">500L</span>);</span><br><span class="line"></span><br><span class="line">        Thread t2 = <span class="keyword">new</span> Thread(() -&gt; account.add(<span class="number">100</span>));</span><br><span class="line">        t2.setName(<span class="string">&quot;存钱线程&quot;</span>);</span><br><span class="line">        t2.start();</span><br><span class="line"></span><br><span class="line">        Thread.sleep(<span class="number">500L</span>);</span><br><span class="line">        <span class="comment">//</span></span><br><span class="line">        System.out.println(t1.getName()+<span class="string">&quot;:&quot;</span>+t1.getState());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Account</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> amount;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存入金额</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> cash</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">int</span> cash)</span></span>&#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:准备存钱&quot;</span>);</span><br><span class="line">        amount = amount + cash;</span><br><span class="line">        notify();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//模拟化时间再做一些事</span></span><br><span class="line">            Thread.sleep(<span class="number">10000L</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 取钱</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> cash</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">get</span><span class="params">(<span class="keyword">int</span> cash)</span></span>&#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:准备取钱&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (amount &lt;= cash)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        amount = amount - cash;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这是第二种导致进入BLOCKED状态的情况.取钱线程先获取到对象锁进入取钱代码块中,由于金额不够,调用wait()等待金额够了再取钱.因为调用wait()失去了对象锁,存钱线程执行.存钱线程存入金额,然后调用了notify(),这个时候取钱线程已唤醒,但是因为存钱线程还未执行完,取钱线程等待锁,所以进入BLOCKED状态.这个就是后面说的<code>一个处于 blocked 状态的线程正在等待一个监视器锁，在其调用 Object.wait 方法之后，以再次进入一个同步的块或方法</code>的解释.</p>
<h2 id="WAITING-等待"><a href="#WAITING-等待" class="headerlink" title="WAITING(等待)"></a>WAITING(等待)</h2><p>线程进入WAITING状态的情况有很多.常见的有以下几种:</p>
<ul>
<li>当前线程调用对象的wait()方法,在等待另外一个线程调用notify()或者notifyAll()</li>
<li>在一个线程中,另一个线程调用了join()方法,该线程会一直等待另外一个线程执行完.</li>
<li>LockSupport.park</li>
</ul>
<p>代码示例1:当线程1调用wait(),线程1进入WAITING状态.线程2调用notify()唤醒线程1.线程1继续执行.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WaitingDemo1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        Object o = <span class="keyword">new</span> Object();</span><br><span class="line">        Thread t1 = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (o)&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;线程1开始执行wait()&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    o.wait();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                System.out.println(<span class="string">&quot;线程1执行完成&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        t1.start();</span><br><span class="line">        <span class="comment">//确保线程1先执行</span></span><br><span class="line">        Thread.sleep(<span class="number">100</span>);</span><br><span class="line"></span><br><span class="line">        Thread t2 = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (o)&#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;线程2开始执行&quot;</span>);</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">2000L</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">                System.out.println(<span class="string">&quot;线程2调用notify()&quot;</span>);</span><br><span class="line">                o.notify();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        t2.start();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;线程1状态:&quot;</span>+t1.getState());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>示例2:在线程1中,另起一个线程线程2.当线程2未执行完时,线程1的状态始终都是WAITING.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WaitingDemo2</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        <span class="comment">//  线程1</span></span><br><span class="line">        Thread t1 = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">            <span class="comment">//线程2</span></span><br><span class="line">            Thread t2 = <span class="keyword">new</span> Thread(() -&gt; &#123;</span><br><span class="line">                <span class="keyword">while</span> (<span class="keyword">true</span>)&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            t2.setName(<span class="string">&quot;线程2&quot;</span>);</span><br><span class="line">            t2.start();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//线程2调用join</span></span><br><span class="line">                t2.join();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line">        t1.setName(<span class="string">&quot;线程1&quot;</span>);</span><br><span class="line">        t1.start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//确保线程1和线程2已开始运行</span></span><br><span class="line">        Thread.sleep(<span class="number">500L</span>);</span><br><span class="line">        System.out.println(t1.getState());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>blocked往往是因为监视锁无法获取,导致无法进入代码块.而waiting主要用来线程之间的协调,进入waiting一般需要另外一个线程执行notify()或者notifyAll()才能被唤醒.blocked更像是被动阻塞的,而waiting更像是主动阻塞的.</p>
<h2 id="TIMED-WAITING-超时等待"><a href="#TIMED-WAITING-超时等待" class="headerlink" title="TIMED_WAITING(超时等待)"></a>TIMED_WAITING(超时等待)</h2><p>大体上与WAITING相似,不同的主要在该状态有超时,如果时间过后,将自动解除该状态.</p>
<ul>
<li>Thread.sleep</li>
<li>带时限（timeout）的 Object.wait</li>
<li>带时限（timeout）的 Thread.join</li>
<li>LockSupport.parkNanos</li>
<li>LockSupport.parkUnti</li>
</ul>
<p>上述方式都会让线程进入该状态.</p>
<p>进入TIMED_WAITING其中的sleep()方法,单独的线程调用也可,不一定非要其他线程协同.与wait()不同的是,它不需要同步语义.例如一般调用wait()都是在同步代码块中,如果不在会报异常.但是sleep()是不需要的.同时,在调用sleep时,是不会让出锁的,而wait()是会让出锁的.</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag"># 多线程</a>
              <a href="/tags/%E5%88%9D%E7%BA%A7/" rel="tag"># 初级</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/10/2.Thread%E4%B8%AD%E5%B8%B8%E7%94%A8%E6%96%B9%E6%B3%95/" rel="prev" title="(二)Thread中常用方法">
      <i class="fa fa-chevron-left"></i> (二)Thread中常用方法
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%8A%B6%E6%80%81"><span class="nav-number">1.</span> <span class="nav-text">状态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%8A%B6%E6%80%81%E5%8F%98%E5%8C%96"><span class="nav-number">2.</span> <span class="nav-text">状态变化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#BLOCKED-%E9%98%BB%E5%A1%9E"><span class="nav-number">3.</span> <span class="nav-text">BLOCKED(阻塞)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WAITING-%E7%AD%89%E5%BE%85"><span class="nav-number">4.</span> <span class="nav-text">WAITING(等待)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#TIMED-WAITING-%E8%B6%85%E6%97%B6%E7%AD%89%E5%BE%85"><span class="nav-number">5.</span> <span class="nav-text">TIMED_WAITING(超时等待)</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">菜鸟</p>
  <div class="site-description" itemprop="description">编程,码农,it,技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">3</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">菜鸟</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
